﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace SegmentDisplay.TestPanel
{
    public class TestPanelViewModel : INotifyPropertyChanged, IDisposable 
    {
        private static Dispatcher _cachedDispatcher = null;
        private void WpfDo(Action called, params object[] args)
        {
            if (_cachedDispatcher == null)
            {
                Application snapshot = Application.Current;
                if (snapshot != null)
                    _cachedDispatcher = snapshot.Dispatcher;
            }
            Dispatcher dispatcher = _cachedDispatcher != null ? _cachedDispatcher : Dispatcher.CurrentDispatcher;
            Delegate target = called as Delegate;
            if (dispatcher.CheckAccess())
                target.DynamicInvoke(args);
            else
                dispatcher.Invoke(target, args);
        }

        System.Threading.Timer timer = null;
        private void timerCallback(object param)
        {
            WpfDo(()=>CurrentTime = DateTime.Now);
        }

        public TestPanelViewModel()
        {
            timer = new System.Threading.Timer(timerCallback, null, 1000, 1000);
        }

        public void Dispose()
        {
            timer.Dispose();
            timer = null;
        }

        private DateTime currentTime = DateTime.Now;
        public DateTime CurrentTime
        {
            get
            {
                return currentTime;
            }
            set
            {
                currentTime = value;
                OnPropertyChanged("CurrentTime");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

        #endregion

    }
}
